package cn.frh.order.service.impl;


import cn.frh.basic.service.impl.BaseServiceImpl;
import cn.frh.basic.util.CodeGenerateUtils;
import cn.frh.basic.util.DistanceUtil;
import cn.frh.basic.util.PageList;
import cn.frh.log.annotation.Log;
import cn.frh.order.domain.AdoptOrder;
import cn.frh.order.domain.OrderAddress;
import cn.frh.order.domain.ProductOrder;
import cn.frh.order.domain.ProductOrderDetail;
import cn.frh.order.mapper.OrderAddressMapper;
import cn.frh.order.mapper.ProductOrderDetailMapper;
import cn.frh.order.mapper.ProductOrderMapper;
import cn.frh.order.query.AdoptOrderQuery;
import cn.frh.order.query.ProductOrderQuery;
import cn.frh.order.service.IProductOrderService;
import cn.frh.org.domain.Employee;
import cn.frh.org.domain.Shop;
import cn.frh.org.mapper.EmployeeMapper;
import cn.frh.org.mapper.ShopMapper;
import cn.frh.pay.constants.AliPayContansts;
import cn.frh.pay.domain.PayBill;
import cn.frh.pay.mapper.PayBillMapper;
import cn.frh.pay.service.IPayBillService;
import cn.frh.product.domain.Product;
import cn.frh.product.mapper.ProductMapper;
import cn.frh.user.domain.Logininfo;
import cn.frh.user.domain.User;
import cn.frh.user.domain.UserAddress;
import cn.frh.user.mapper.UserAddressMapper;
import cn.frh.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

@Service
public class ProductOrderServiceImpl extends BaseServiceImpl<ProductOrder> implements IProductOrderService {

    @Autowired
    private ProductOrderMapper productOrderMapper;
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductOrderDetailMapper productOrderDetailMapper;
    @Autowired
    private PayBillMapper payBillMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IPayBillService payBillService;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;


    @Override
    @Transactional
    @Log(value = "提交服务订单")
    public String submit(Map<String, Object> params, Logininfo currentLogininfo) {
        Long addressId = Long.parseLong(params.get("address_id").toString());
        Long productId = Long.parseLong(params.get("product_id").toString());
        Long pay_method = Long.parseLong(params.get("pay_method").toString());
        Long productNum = Long.parseLong(params.get("product_num").toString());
        Product product = productMapper.loadByIdDetail(productId);
        if (product.getSalecount() == null) {
            product.setSalecount(0);
        }
        product.setSalecount((int) (product.getSalecount() + productNum));
        productMapper.update(product);
        UserAddress userAddress = userAddressMapper.loadById(addressId);
        //1创建订单
        //1.1 创建订单
        User user = userMapper.loadByLogininfoId(currentLogininfo.getId());
        ProductOrder productOrder = getProductOrder(params, userAddress, product, user);
        productOrderMapper.save(productOrder);
        //1.2 保存关联表 orderAdress productOrderDetail

        System.out.println(productOrder.getId());
        OrderAddress orderAddress = userAddress2orderAddress(userAddress);
        orderAddress.setOrder_id(productOrder.getId());
        orderAddress.setOrderSn(productOrder.getOrderSn());
        orderAddressMapper.save(orderAddress);

        ProductOrderDetail productOrderDetail = product2productOrderDetail(product);
        productOrderDetail.setOrder_id(productOrder.getId());
        productOrderDetailMapper.save(productOrderDetail);

        // 2 创建支付单
        PayBill payBill = order2PayBill(pay_method, productOrder, user);
        payBillMapper.save(payBill);

        // 3 订单倒计时取消处理
        /*QuartzJobInfo info = new QuartzJobInfo();
        String jobName = JobConstants.JOB_TYPE_PRODUCT_ORDER_CANCEL + productOrder.getId();
        Map<String, Object> map = new HashMap<>();
        map.put("orderId", productOrder.getId());
        map.put("type", JobConstants.JOB_TYPE_PRODUCT_ORDER_CANCEL);
        Date fireDate = productOrder.getLastPayTime();
        info.setJobName(jobName);
        info.setParams(map);
        info.setFireDate(fireDate);
        quartzService.addJob(info);*/
        // 4 跳转到支付页面,通过调用支付接口，要把这个数据返回前台，前台处理后跳转支付宝支付页面
        String payData = payBillService.pay(payBill);
        return payData;
    }

    private PayBill order2PayBill(Long pay_method, ProductOrder productOrder, User user) {
        PayBill payBill = new PayBill();
        payBill.setDigest(productOrder.getDigest());
        payBill.setMoney(productOrder.getPrice());
        payBill.setUnionPaySn(productOrder.getPaySn());
        payBill.setState(0);
        payBill.setLastPayTime(productOrder.getLastPayTime());
        payBill.setPayChannel(pay_method);
        payBill.setBusinessType(AliPayContansts.PRODUCT_ORDER);
        payBill.setBusinessKey(productOrder.getId());
        payBill.setCreateTime(new Date());
        payBill.setUser_id(productOrder.getUser_id());
        payBill.setNickName(user.getUsername());
        payBill.setShop_id(productOrder.getShop_id());
        return payBill;
    }

    private ProductOrderDetail product2productOrderDetail(Product product) {
        ProductOrderDetail productOrderDetail = new ProductOrderDetail();
        BeanUtils.copyProperties(product, productOrderDetail);
        return productOrderDetail;
    }

    private OrderAddress userAddress2orderAddress(UserAddress userAddress) {
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(userAddress, orderAddress);
        orderAddress.setContacts(userAddress.getContacts());
        orderAddress.setCreateTime(new Date());
        return orderAddress;
    }
    private ProductOrder getProductOrder(Map<String, Object> params, UserAddress userAddress, Product product, User user) {
        Long productNum = Long.parseLong(params.get("product_num").toString());
        ProductOrder productOrder = new ProductOrder();

        productOrder.setDigest("[服务订单]购买" + productNum + "次" + product.getName() + "服务！");
        productOrder.setState(0);
        BigDecimal price = product.getSaleprice().multiply(new BigDecimal(productNum));
        productOrder.setPrice(price);
        productOrder.setOrderSn(CodeGenerateUtils.generateOrderSn(user.getId()));
        Date lastPayTime = new Date(System.currentTimeMillis() + 60 * 1000); //当前时间+30分钟
        productOrder.setLastPayTime(lastPayTime);
        productOrder.setProduct_id(product.getId());
        productOrder.setUser_id(user.getId());
        Shop nearestShop = DistanceUtil.getNearestShop(DistanceUtil.getPoint(userAddress.getFullAddress()), shopMapper.loadAll());
        productOrder.setShop_id(nearestShop.getId());
        productOrder.setPaySn(CodeGenerateUtils.generateUnionPaySn());
        return productOrder;
    }

    @Transactional
    @Log(value = "提交服务订单")
    public PageList<ProductOrder> admin(ProductOrderQuery query, Logininfo currentLogininfo) {
        Employee employee = employeeMapper.loadByLogininfoId(currentLogininfo.getId());
        if (employee.getShop_id()!=null){
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }
}
